//
//  SignUpViewController.m
//  babyMemoryPro
//
//  Created by student on 15-6-26.
//  Copyright (c) 2015年 niit. All rights reserved.
//

#import "SignUpViewController.h"
#import <AddressBook/AddressBook.h>
#import "DSLolita-PrefixHeader.pch"
#import "LolitaFunctions.h"


@interface SignUpViewController ()<UITextFieldDelegate , UIImagePickerControllerDelegate , UINavigationControllerDelegate>{

    UIView *viewLoading;
    BOOL toUploadImage;
    BOOL photoUploaded;
    
    NSArray *arrContacts;
    CGRect frameDefault;

}

@end

@implementation SignUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)choosePhoto:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    //if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    //picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //else
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
}

- (IBAction)sign:(id)sender {
    NSString *errorMessage = [self checkUserDetails];
    if (![errorMessage length]){
        
        NSCharacterSet *whiteNewChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *email = [self.adress.text stringByTrimmingCharactersInSet:whiteNewChars];
        NSString *username = [self.name.text stringByTrimmingCharactersInSet:whiteNewChars];
        NSString *password = [self.password.text stringByTrimmingCharactersInSet:whiteNewChars];
        NSString *phone = [self.iphone.text stringByTrimmingCharactersInSet:whiteNewChars];
        
        
        AVUser *user = [AVUser user];
        [user setUsername:username];
        [user setPassword:password];
        [user setEmail:email];
        user[@"phone"] = phone;
        
        
        //viewLoading = [_LolitaFunctions showLoadingViewWithText:@"正在注册" inView:self.view];
        
        [user signUpInBackgroundWithBlock:^(BOOL succeeded , NSError *error) {
            if (!error){
                [self checkIfToUploadImage];
            }
            else{
                //[_LolitaFunctions hideLoadingView:viewLoading];
                [[[UIAlertView alloc] initWithTitle:@"注册失败"
                                            message:[error userInfo][@"error"]
                                           delegate:nil
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil, nil] show];
            }
        }];
    }else{
        [[[UIAlertView alloc] initWithTitle:@"注册失败"
                                    message:errorMessage
                                   delegate:nil
                          cancelButtonTitle:@"确定"
                          otherButtonTitles:nil, nil] show];
    }

}
- (void)setupSignUpView {
    
    frameDefault = self.view.frame;
    
    [self setTitle:@"注册"];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [self.adress setLeftViewMode:UITextFieldViewModeAlways];
    [self.adress setLeftView:[[LolitaFunctions sharedObject] leftViewForTextFieldWithImage:@"email"]];
    
    [self.name setLeftViewMode:UITextFieldViewModeAlways];
    [self.name setLeftView:[[LolitaFunctions sharedObject] leftViewForTextFieldWithImage:@"user_grey"]];
    
    [self.password setLeftViewMode:UITextFieldViewModeAlways];
    [self.password setLeftView:[[LolitaFunctions sharedObject] leftViewForTextFieldWithImage:@"password_grey"]];
    
    [self.iphone setLeftViewMode:UITextFieldViewModeAlways];
    [self.iphone setLeftView:[[LolitaFunctions sharedObject] leftViewForTextFieldWithImage:@"phone"]];
    
    [self.buttonSignUp setBackgroundColor:[[LolitaFunctions sharedObject] colorWithR:36 g:164 b:193 alpha:1.0f]];
    [self.buttonSignUp.layer setCornerRadius:3.0f];
    
    [self.imageViewProfile.layer setBorderColor:[UIColor colorWithWhite:220/255.0f alpha:1.0f].CGColor];
    [self.imageViewProfile.layer setBorderWidth:3.0f];
    
    [self.imageViewProfile.layer setCornerRadius:self.imageViewProfile.frame.size.width/2.0f];
}
- (void)resetTextFields {
    [self.adress setText:nil];
    [self.name setText:nil];
    [self.password setText:nil];
    [self.iphone setText:nil];
}

-(void)resignRespondersForTextFields {
    [UIView animateWithDuration:0.24
                     animations:^{
                         [self.view setFrame:frameDefault];
                     }
                     completion:nil];
    
    [self.adress resignFirstResponder];
    [self.name resignFirstResponder];
    [self.password resignFirstResponder];
    [self.iphone resignFirstResponder];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    CGRect newFrame = self.view.frame;
    newFrame.origin.y = -textField.tag * textField.frame.size.height;
    [UIView animateWithDuration:0.24
                     animations:^{
                         [self.view setFrame:newFrame];
                     }completion:^(BOOL finished){
                         
                     }];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == self.adress)
        [self.name becomeFirstResponder];
    else if (textField == self.name)
        [self.password becomeFirstResponder];
    else if (textField == self.password)
        [self.iphone becomeFirstResponder];
    else
        [self resignRespondersForTextFields];
    return YES;
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];

}

- (BOOL)checkPhoneNumber:(NSString *)phoneNumber {
    
    NSError *error = NULL;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
    
    NSRange inputRange = NSMakeRange(0, [phoneNumber length]);
    NSArray *matches = [detector matchesInString:phoneNumber options:0 range:inputRange];
    
    BOOL verified = NO;
    
    if ([matches count] != 0) {
        // found match but we need to check if it matched the whole string
        NSTextCheckingResult *result = (NSTextCheckingResult *)[matches objectAtIndex:0];
        
        if ([result resultType] == NSTextCheckingTypePhoneNumber && result.range.location == inputRange.location && result.range.length == inputRange.length) {
            // it matched the whole string
            verified = YES;
        }
        else {
            // it only matched partial string
            verified = NO;;
        }
    }
    
    return verified;
}
-(NSString *)checkUserDetails{
    NSCharacterSet *whithNewChars=[NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *email=[self.adress.text stringByTrimmingCharactersInSet:whithNewChars];
    NSString *username =[self.name.text stringByTrimmingCharactersInSet:whithNewChars];
    NSString *password =[self.password.text stringByTrimmingCharactersInSet:whithNewChars];
    NSString *phone =[self.iphone.text stringByTrimmingCharactersInSet:whithNewChars];

    BOOL phoneVerified=[self checkPhoneNumber:phone];

    NSString *message=@"";
    if (![[LolitaFunctions sharedObject] validateEmail:email]) {
        message=@"邮箱格式有误";
        
    }
    if ([username length]<6) {
        if ([message length]) {
            message=[NSString stringWithFormat:@"%@,",message];
            message=[NSString stringWithFormat:@"%@用户名过于简单，请重新输入",message];
        }
    }if ([password length]<6) {
        if ([message length]) {
            message=[NSString stringWithFormat:@"%@,",message];
            message=[NSString stringWithFormat:@"%@密码过于简单，请重新输入",message];
        }
    }if (!phoneVerified) {
        if ([message length]) {
            message=[NSString stringWithFormat:@"%@,",message];
            message=[NSString stringWithFormat:@"%@无效的手机号码",message];
        }
    }
    return message;
}
-(void)signUpSuccess{
    [[LolitaFunctions sharedObject] hideLoadingView:viewLoading];
    [self resetTextFields];
    [self.navigationController popViewControllerAnimated:YES];
    
    NSString *message=@"注册成功";
    if (!photoUploaded) {
        message=[NSString stringWithFormat:@"%@,但没有上传头像成功",message];
    }
    [[[UIAlertView alloc] initWithTitle:@"注册" message:message
                                 delegate:nil
                        cancelButtonTitle:@"确定"
                        otherButtonTitles:nil, nil] show];

}


-(void)checkIfToUploadImage {
    if(toUploadImage) {
        AVUser *currentUser = [AVUser currentUser];
        NSString *strImageName = [NSString stringWithFormat:@"%@.png",currentUser.objectId];
        
        NSData *imageData = UIImagePNGRepresentation(self.imageViewProfile.image);
        AVFile *imageFile = [AVFile fileWithName:strImageName data:imageData];
        
        [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
            if (!error) {
                photoUploaded  = YES;
                [currentUser setObject:imageFile forKey:@"avatar"];
                [currentUser saveInBackgroundWithBlock:^(BOOL succeeded , NSError *error){
                    if (!error){
                        photoUploaded = YES;
                    }else{
                        photoUploaded = NO;
                    }
                    
                    [self signUpSuccess];
                }];
            }
        }];
    }
}
#pragma mark - UIImagePickerController Delegage

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    toUploadImage = YES;
    
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.imageViewProfile.image = chosenImage;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark - Touch Mechods

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UIView *viewTouched = [[touches anyObject] view];
    if (![viewTouched isKindOfClass:[UITextField class]]){
        [self resignFirstResponder];
    }
}

@end
